//
//  SportCircleDetail.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/11.
//

import SwiftUI
import URLImage
import KeyboardAvoider
import Combine




struct SportCircleDetail: View {
    @EnvironmentObject var appState: AppState
    @State var dynamicitem:DynamicItem
    @StateObject private var emojiData = EmojiData()
    @State private var inputText = ""
    @State private var showEmojiKeyboard = false
    @FocusState private var isKeyboardFocused: Bool
    @State private var keyboardHeight: CGFloat = 0

    
    var body: some View {
        VStack {
            HStack {
                HStack {
                    Button(action: {
                        appState.navigateBack()
                    }) {
                        Image("back")
                    }
                    .frame(width: 16,height: 16)
                    Spacer()
                    Text("详情")
                        .font(.system(size: 18))
                        .foregroundStyle(.white)
                    Spacer()
                    Button(action: {
                        appState.navigateTo(.postSportMoment)
                    }) {
                        Image("posticon")
                    }
                    .frame(width: 24,height: 24)
                }
                .padding(.horizontal,12)
                .frame(height: 44)
                .padding(.top,44)
            }
            ScrollView (.vertical,showsIndicators: false){
                VStack {
                    DetailCell(dynamicitem:$dynamicitem)
                    Spacer().frame(height: 20)
                    Divider().frame(height: 0.5).background(.white).padding(.horizontal,16)
                    
                    Spacer().frame(height: 16)
                    HStack{
                        Text("评论 2").font(.system(size: 16)).foregroundStyle(.white)
                        Spacer()
                    }.padding(.horizontal,16)
                    Spacer().frame(height: 20)
                    CommentView(dynamicitem: $dynamicitem)
                    
                    Spacer()
                }
            }.scrollDisabled(true)
            
            Spacer()
            HStack {
                TextField("发布评论", text: $inputText)
                    .focused($isKeyboardFocused)
                    .textFieldStyle(RoundedBorderTextFieldStyle())
                    .frame(height: 46)
                    .lineLimit(5)
                    .padding(.leading,16)
                Spacer()
                Button {
                    showEmojiKeyboard.toggle()
                    // 表情键盘动态显示
                    if showEmojiKeyboard {
                        isKeyboardFocused = false
                    }else {
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25) {
                            isKeyboardFocused = true
                        }
                    }
                } label: {
                    Image(showEmojiKeyboard ?"keyboard":"face1")
                        .resizable()
                        .frame(width: 37,height: 37)
                        .clipShape(Circle())
                        .padding(.trailing,16)
                }
            }
            .frame(height: 97)
            .background(Color(hex: "#1E1E1E"))
            .offset(y: -keyboardHeight)
            .onReceive(Publishers.keyboardHeight) { height in
                keyboardHeight = height
            }
            if showEmojiKeyboard {
                EmojiKeyboard(data: emojiData, inputText: $inputText)
                    .transition(.move(edge: .bottom))
            }
        }
        .navigationBarHidden(true)
        .background(Color(hex: "#0A0A0A"))
        .edgesIgnoringSafeArea(.all)
        .animation(.easeInOut, value: showEmojiKeyboard)
        .onTapGesture {
            // 点击空白处隐藏键盘和表情面板
            isKeyboardFocused = false
            showEmojiKeyboard = false
        }
        .onAppear {
//            emojiData.loadEmojis()
        }
    }
   
}


struct DetailCell: View {
    @Binding var dynamicitem: DynamicItem
    @State private var isExpanded = false
    var body: some View {
        VStack(alignment: .leading ,spacing: 16) {
            // 用户信息栏
            HStack(spacing: 10) {
                if let urlStr = dynamicitem.avatar,let url = URL(string: urlStr) {
                    URLImage(url: url) { image in
                        image
                            .resizable()
                            .frame(width: 49, height: 49)
                            .clipShape(Circle())
                    }
                }else {
                    Image("21")
                        .resizable()
                        .frame(width: 49, height: 49)
                        .clipShape(Circle())
                }
                
                VStack(alignment: .leading) {
                    Text(dynamicitem.nickname)
                        .font(.system(size: 16))
                        .foregroundStyle(.white)
                    Text(String(dynamicitem.createTime))
                        .font(.system(size: 14))
                        .foregroundStyle(Color(hex: "#8A8A8A"))
                }
                Spacer()
                Button(action: {
                    
                }) {
                    Text("关注")
                        .font(.system(size: 14))
                        .foregroundStyle(Color(hex: "#242424"))
                        .frame(width: 76,height: 30)
                        .background(Color(hex: "#00E9DA"))
                        .cornerRadius(15)
                }
            }
            .padding(.horizontal,16)
            .padding(.top,20)
            
            // 正文内容
            Text(dynamicitem.content)
                .font(.system(size: 16))
                .foregroundStyle(.white)
                .padding(.horizontal,16)
                .padding(.top,12)
                .lineLimit(isExpanded ? nil : 3)
                .onTapGesture { isExpanded.toggle() }
            
            if let address = dynamicitem.address,!address.isEmpty {
                ZStack {
                    Image("map")
                        .resizable()
                        .frame(height: 74)
                    
                }.padding(.horizontal,16)
            }
            // 九宫格图片
            if !dynamicitem.mediaUrls.isEmpty {
                PostImagesView(images: dynamicitem.mediaUrls)
                    .padding(.horizontal,16)
            }
        }
        .background(.clear)
    }
}

struct CommentView: View {
    @Binding var dynamicitem: DynamicItem
    @State private var isExpanded = false
    var body: some View {
        VStack(alignment: .leading ,spacing: 8) {
            // 用户信息栏
            HStack(spacing: 10) {
                if let urlStr = dynamicitem.avatar,let url = URL(string: urlStr) {
                    URLImage(url: url) { image in
                        image
                            .resizable()
                            .frame(width: 36, height: 36)
                            .clipShape(Circle())
                    }
                }else {
                    Image("21")
                        .resizable()
                        .frame(width: 36, height: 36)
                        .clipShape(Circle())
                }
                
                VStack(alignment: .leading) {
                    Text(dynamicitem.nickname)
                        .font(.system(size: 16))
                        .foregroundStyle(.white)
                    Text(String(dynamicitem.createTime))
                        .font(.system(size: 12))
                        .foregroundStyle(Color(hex: "#CACACA"))
                }
                Spacer()
                Button(action: {
//                    isLike.toggle()
//                    if isLike {
//                        proModel.dynamicLike(dynamicId: dynamicitem.dynamicId)
//                    }else {
//                        proModel.dynamicUnlike(dynamicId: dynamicitem.dynamicId)
//                    }
                }) {
//                    Label("\(dynamicitem.likeCount)", image: isLike ? "like" : "dianzan")
                    Label("2", image:"dianzan").foregroundStyle(.white)

                }
                
            }
            .padding(.horizontal,16)
            // 正文内容
            Text(dynamicitem.content)
                .font(.system(size: 16))
                .foregroundStyle(.white)
                .padding(.leading,63)
                .padding(.trailing,16)
                .lineLimit(isExpanded ? nil : 3)
                .onTapGesture { isExpanded.toggle() }
        }
        .background(.clear)
    }
}

extension Publishers {
    static var keyboardHeight: AnyPublisher<CGFloat, Never> {
        let willShow = NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)
            .map { ($0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0 }
        
        let willHide = NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)
            .map { _ in CGFloat(0) }
        
        return MergeMany(willShow, willHide)
            .eraseToAnyPublisher()
    }
}


